package com.agriculture.service.impl;

import com.agriculture.mapper.UserMapper;
import com.agriculture.service.UserService;
import agriculture.system.api.model.User;

import com.agriculture.util.AESUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        // 1. 检查用户名是否已存在
        User existingUser = userMapper.findByPhone(user.getPhone());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 2. 对明文密码进行 AES 加密
        String encryptedPassword = AESUtil.encrypt(user.getPassword());
        user.setPassword(encryptedPassword);

        // 3. 如果 status 为空，默认设置为 1（启用）
        if (user.getStatus() == null) {
            user.setStatus(1);
        }

        // 4. 插入数据库
        userMapper.insertUser(user);
    }

    @Override
    public User login(String phone, String password) {
        // 1. 根据用户名查找用户
        User user = userMapper.findByPhone(phone);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 2. 解密数据库中的加密密码
        String decryptedPassword = AESUtil.decrypt(user.getPassword());

        // 3. 比对用户输入的明文密码与解密后的密码是否一致
        if (!decryptedPassword.equals(password)) {
            throw new RuntimeException("用户名或密码错误");
        }

        return user;
    }

    @Override
    public User findUserById(Long userId) {
        return userMapper.getUserById(userId);
    }



    @Override
    @Transactional
    public User updateUser(User user) {
        int rows = userMapper.updateUser(user);
        if (rows > 0) {
            // 更新后重新查询返回最新数据
            return userMapper.getUserById(user.getId());
        }
        return null;
    }
}
